package webshowAjax;

import com.alibaba.fastjson.JSON;
import dao.User;
import tools.InfoPack;
import utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.sampled.Line;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BirNearServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取最近生日人的表格

        // 修改编码格式
        req.setCharacterEncoding("UTF-8");		// 接受到的
        resp.setContentType("text/html; charset=UTF-8");		// 修改发送的

        // 数据库调用相关
        Connection connection = null;
        PreparedStatement pStatement = null;
        ResultSet rsSet = null;

        // 连接数据库
        connection = JDBCUtils.getConnection();
        // 创建sql语句 未来7天
//        String sql = "select userName,userBir,userNum from student where TIMESTAMPDIFF(day,now(),userBir)<=7 and TIMESTAMPDIFF(day,now(),userBir)>=0 order by userBir";
        String sql = "select userName,date_format(userBir,'%m-%d') as userBir,userNum from student where TIMESTAMPDIFF(day,date_format(now(),'0000-%m-%d'),date_format(userBir,'0000-%m-%d') )<=7 and TIMESTAMPDIFF(day,date_format(now(),'0000-%m-%d'),date_format(userBir,'0000-%m-%d') )>=0  order by date_format(userBir,'0000-%m-%d')";

        // 与上sql问号一一对应
        if("true".equals(req.getParameter("limit")))   sql += " limit 3";
        try {
            pStatement = connection.prepareStatement(sql); // 传递
            rsSet = pStatement.executeQuery();      // 结果
            resp.getWriter().append(InfoPack.RstoJson(rsSet));  // 发送(打包)
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JDBCUtils.close(connection, pStatement, rsSet);    // 关闭连接
        }
    }
}
